﻿
using OA.Core;
using OA.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using Microsoft.Extensions.Caching.Memory;
using OA.Web.Code;
using Microsoft.AspNetCore.Http;
using OA.Web.Attribute;
using Microsoft.AspNetCore.Mvc;
using OA.Model.DB;
using OA.Core.Helper;
using X.PagedList;
using OA.Core.EF;

namespace OA.Web.Areas.Member.Controllers
{
    public class VoteController : BaseMemberController
    {
        private IMemoryCache _cache;
        private ICookie _cookie;
        public VoteController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
            _cookie = cookie;
        }

        [MyActionFilterAttribute("001010", "我的投票", "个人中心", true, "iconxianchangtoupiao")]
        public IActionResult Index()
        {
            return View();
        }

        [MyActionFilterAttribute("001010", "我的投票")]
        public IActionResult GetData(string keyWord, int page = 1, int limit = 12)
        {
            ViewBag.KeyWord = keyWord;
            Expression<Func<EmployeeVoteView, bool>> where = m => m.EmpID == this.EmpID;
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                where = where.AndAlso<EmployeeVoteView>(m => m.Title.Contains(keyWord));
            }
            var list = this.dbContextFactory.DbContext.EmployeeVoteView.Where(where).OrderByDescending(m => m.ID).ToPagedList(page, limit);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.TotalItemCount,
                data = list
            };
            return Json(result);

        }


        [MyActionFilterAttribute("001010", "我的投票")]
        public IActionResult Write(int id)
        {
            EmployeeVote infoEmployeeVote=this.dbContextFactory.DbContext.EmployeeVote.Where(m => m.ID == id).FirstOrDefault();

            if (infoEmployeeVote == null || infoEmployeeVote.EmpID != this.EmpID)
            {
                return Redirect($"/Member/TestPaper/Index?msg=没有找到该投票");
            }

            Vote infoVote = this.GetInfo<Vote>(infoEmployeeVote.VoteID);
            List<EmployeeVoteSelect> listResult = this.dbContextFactory.DbContext.EmployeeVoteSelect.Where(m => m.VoteID == infoVote.ID && m.EmpID == Info.EmpID).ToList();
            ViewBag.Vote = infoVote;
            List<VoteItem> items = new List<VoteItem>();
            if (!string.IsNullOrWhiteSpace(infoVote.VoteItemContent))
            {
                items = JsonHelper.DeserializeList<VoteItem>(infoVote.VoteItemContent);
            }
            if (items == null || items.Count == 0)
            {
                items = new List<VoteItem>() { new VoteItem() { } };
            }
            ViewBag.Result = listResult;
            return View(items);

        }

        [HttpPost]
        [MyActionFilterAttribute("001010", "我的投票")]
        public IActionResult Write(int id, List<EmployeeVoteSelect> MyItems)
        {
            EmployeeVote infoEmployeeVote = this.dbContextFactory.DbContext.EmployeeVote.Where(m => m.ID == id).FirstOrDefault();

            if (infoEmployeeVote == null || infoEmployeeVote.EmpID != this.EmpID)
            {
                return Redirect($"/Member/TestPaper/Index?msg=没有找到该投票");
            }

            Vote infoVote = this.GetInfo<Vote>(infoEmployeeVote.VoteID);
            List<EmployeeVoteSelect> listResult = this.dbContextFactory.DbContext.EmployeeVoteSelect.Where(m => m.VoteID == infoVote.ID && m.EmpID == Info.EmpID).ToList();
            ViewBag.Vote = infoVote;
            List<VoteItem> items = new List<VoteItem>();
            if (!string.IsNullOrWhiteSpace(infoVote.VoteItemContent))
            {
                items = JsonHelper.DeserializeList<VoteItem>(infoVote.VoteItemContent);
            }
            if (items == null || items.Count == 0)
            {
                items = new List<VoteItem>() { new VoteItem() { } };
            }
            if (items.Count != MyItems.Count)
            {
                return Redirect($"/Member/Vote/Write?id={id}&msg=错误格式不正确");
            }

            var question = items.Select(m => m.ID).ToList();
            var answer = MyItems.Select(m => m.VoteItemID).ToList();
            if (question.Except(answer).Count() > 0)//判断是否又差集
            {
                return Redirect($"/Member/Vote/Write?id={id}&msg=错误格式不正确");
            }

            List<EmployeeVoteSelect> addItem = new List<EmployeeVoteSelect>();
            List<EmployeeVoteSelect> updateItems = new List<EmployeeVoteSelect>();
            foreach (EmployeeVoteSelect item in MyItems)
            {
                VoteItem itemVote = items.Where(m => m.ID == item.VoteItemID).FirstOrDefault();
                if(itemVote==null|| itemVote.Type!=item.Type)
                {
                    return Redirect($"/Member/Vote/Write?id={id}&msg=错误格式不正确");
                }
                item.Options = string.Join(",", item.MyOptions);
                var myItem= listResult.Where(m => m.VoteItemID == item.VoteItemID).FirstOrDefault();
                if (myItem == null)
                {
                    item.CreateDateTime = DateTime.Now;
                    item.EmpID = Info.EmpID;
                    item.Status = 1;
                    item.VoteID = infoVote.ID;
                    addItem.Add(item);
                }
                else if (myItem.Options != item.Options)
                {
                    updateItems.Add(item);
                }
            }

            using (var trn=this.dbContextFactory.DbContext.Database.BeginTransaction())
            {
                try
                {
                    if (addItem.Count > 0)
                    {
                        this.AddRange<EmployeeVoteSelect>(addItem);
                    }
                    if (updateItems.Count > 0)
                    {
                        foreach (EmployeeVoteSelect updateItem in updateItems)
                        {
                            EmployeeVoteSelect item = listResult.Where(m => m.VoteItemID == updateItem.VoteItemID).FirstOrDefault();
                            this.Update<EmployeeVoteSelect>(item, updateItem, new string[] { "Options" });

                        }
                    }

                    EmployeeVote updateEmployeeVote = new EmployeeVote();
                    updateEmployeeVote.Status = 1;
                    updateEmployeeVote.FillingDate = DateTime.Now;
                    this.Update<EmployeeVote>(infoEmployeeVote, updateEmployeeVote,new string[] { "Status", "FillingDate" });
                    trn.Commit();
                    return Redirect($"/Member/Vote/Show/{id}");
                }
                catch(Exception ex)
                {
                    trn.Rollback();
                    ViewBag.Result = MyItems;
                    return View(items);
                }                
            }
        }
        [MyActionFilterAttribute("001010", "我的投票")]
        public IActionResult Show(int id)
        {
            EmployeeVote infoEmployeeVote = this.dbContextFactory.DbContext.EmployeeVote.Where(m => m.ID == id).FirstOrDefault();
            if (infoEmployeeVote == null || infoEmployeeVote.EmpID != this.EmpID)
            {
                return Redirect($"/Member/TestPaper/Index?msg=没有找到该投票");
            }            
            Vote infoVote = this.GetInfo<Vote>(infoEmployeeVote.VoteID);
            List<EmployeeVoteSelect> listResult = this.dbContextFactory.DbContext.EmployeeVoteSelect.Where(m => m.VoteID == infoVote.ID && m.EmpID == Info.EmpID).ToList();
            ViewBag.Vote = infoVote;
            List<VoteItem> items = new List<VoteItem>();
            if (!string.IsNullOrWhiteSpace(infoVote.VoteItemContent))
            {
                items = JsonHelper.DeserializeList<VoteItem>(infoVote.VoteItemContent);
            }
            if (items == null || items.Count == 0)
            {
                items = new List<VoteItem>() { new VoteItem() { } };
            }
            ViewBag.Result = listResult;

            //List<dynamic> data = new List<dynamic>();

            //List<dynamic> abc2 = new List<dynamic>();

            //foreach (dynamic item in data)
            //{
            //    abc2.Add(item);
            //    dynamic item2 = JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(item));
            //    item2.name = "";
            //    abc2.Add(item2);
            //}

            return View(items);

        }

    }
}